package com.stephen.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by stephen on 2021-03-28 16:54 .
 * Description: response实现文件下载
 */
public class FileDownloadDemo extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取下载路径
        String path = "C:\\Users\\stephen\\Desktop\\git_projects\\javaweb-servlet\\src\\main\\resources\\中国.png";
        System.out.println("下载文件的路径: " + path);
        // 2. 获取文件名,截取最后一个斜杠后的内容
        String fileName = path.substring(path.lastIndexOf("\\") + 1);
        // 3. 让浏览器支持下载,注意中文编码问题
        resp.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        // 4. 获取文件输入流
        FileInputStream in = new FileInputStream(path);
        // 5. 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 6. 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        // 7. 将FileInputStream流写入到buffer缓冲区,使用OutputStream将缓冲区数据输出到客户端
        // != -1 或者 > 0 都表示已经读取完成
        try {
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { // 关闭流,先开启的后关闭
            closeIgnoringIOException(out);
            closeIgnoringIOException(in);
        }
    }

    // 关闭流的通用方法
    private static void closeIgnoringIOException(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
